﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
using System.Diagnostics;

namespace MobileSMSRemote
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadSmsIntercepter();

            List<ISmsCommand> commands = new List<ISmsCommand>();
            commands.Add(new DateTimeSmsCommand());
            commands.Add(new GpsSmsCommand());
            commands.Add(new ProcessSmsCommand());

            foreach (ISmsCommand command in commands)
                comboBoxSMSCommand.Items.Add(command);
        }

        #region SmsInterceptor Region

        MessageInterceptor _smsInterceptor = null;
        private void LoadSmsIntercepter()
        {
            // Default constructor indicates that message handling should occur
            // on the main application thread, and message should be passed
            // to other message interceptors and to the SMS message reader
            _smsInterceptor = new MessageInterceptor(InterceptionAction.NotifyAndDelete);
            // The name is reported in the form of the Contact's File As field
            // Therefore must check for "Smith, John", not "John Smith"
            _smsInterceptor.MessageCondition =
                new MessageCondition(MessageProperty.Subject,
                MessagePropertyComparisonType.StartsWith, "30days:", true);
            _smsInterceptor.MessageReceived += SmsInterceptor_MessageReceived;
        }

        void SmsInterceptor_MessageReceived(object sender, MessageInterceptorEventArgs e)
        {
            if (checkBoxAllowRemoteCommands.Checked == false)
                return;

            // Cast to SmsMessage to access message body
            // Not expecting to receive any non-SMS messages but use "as" to
            // cast to be extra safe
            SmsMessage newMessage = e.Message as SmsMessage;
            if (newMessage != null)
            {
                string command = newMessage.Body.Replace("30days:", string.Empty).Trim();
                string address = newMessage.From.Address;

                if (command.Contains("result:"))
                {
                    command = command.Replace("result:", string.Empty);

                    MessageBox.Show(command, "Alert!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                }
                else if (command.Contains("command:"))
                {
                    command = command.Replace("command:", string.Empty);

                    ISmsCommand smsCommand = SmsCommandHelper.GetSmsCommandByName(command);

                    LogCommand(address, DateTime.Now.ToString(), command);

                    SendSms(address, string.Format("result:{0}='{1}'", smsCommand.Name, smsCommand.Action()));
                }
            }
        }

        private void frmMain_Closed(object sender, EventArgs e)
        {
            if (_smsInterceptor != null)
            {
                // Remove event handler to assure proper registry cleanup
                _smsInterceptor.MessageReceived -= SmsInterceptor_MessageReceived;
                _smsInterceptor.Dispose();
            }
        }

        #endregion

        private void LogCommand(string address, string time, string command)
        {
            listView.Items.Add(new ListViewItem(new string[] { address, time, command }));
        }

        private void menuItemSend_Click(object sender, EventArgs e)
        {
            SendSms(textBoxPhoneNumber.Text, "command:" + ((ISmsCommand)comboBoxSMSCommand.SelectedItem).Name);
        }

        private void SendSms(string address, string body)
        {
            SmsMessage smsMessage = new SmsMessage();

            //Set the message body and recipients
            smsMessage.Body = "30days:" + body;
            smsMessage.To.Add(new Recipient(address));

            //Send the SMS message.
            smsMessage.Send();
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuItemAbout_Click(object sender, EventArgs e)
        {
            frmAbout aboutForm = new frmAbout();
            aboutForm.ShowDialog();
        }

        private void menuItemClearLog_Click(object sender, EventArgs e)
        {
            listView.Items.Clear();
        }
    }
}